import { FC, useState, useEffect, useRef } from "react";
import styles from "./index.module.less";

interface AISummaryProps {
  summary?: string;
  isLoading?: boolean;
}

const AISummary: FC<AISummaryProps> = ({ summary, isLoading = false }) => {
  const [displayText, setDisplayText] = useState<string>("");
  const [isTyping, setIsTyping] = useState<boolean>(false);
  const prevLoadingRef = useRef<boolean>(isLoading);
  const prevSummaryRef = useRef<string | undefined>(summary);

  useEffect(() => {
    // 检测是否需要触发打字机效果
    const shouldStartTyping = 
      // 从loading状态变为非loading状态
      (prevLoadingRef.current && !isLoading && summary) || 
      // 或者summary发生变化且不在loading状态
      (!isLoading && summary && prevSummaryRef.current !== summary);
    
    if (shouldStartTyping) {
      setIsTyping(true);
      setDisplayText("");
      
      const textToType = summary;
      let currentIndex = 0;
      
      const typingInterval = setInterval(() => {
        if (currentIndex < textToType.length) {
          setDisplayText(textToType.substring(0, currentIndex + 1));
          currentIndex++;
        } else {
          clearInterval(typingInterval);
          setIsTyping(false);
        }
      }, 30); // 打字速度，可以根据需要调整
      
      return () => clearInterval(typingInterval);
    } else if (isLoading) {
      setDisplayText("");
    } else if (!isLoading && !isTyping && summary && prevSummaryRef.current === summary) {
      // 直接显示完整内容（如果不需要触发打字机效果）
      setDisplayText(summary);
    }
    
    // 更新引用值
    prevLoadingRef.current = isLoading;
    prevSummaryRef.current = summary;
  }, [isLoading, summary]);

  return (
    <div className={`${styles["ai-summary"]} ${isLoading ? styles["loading"] : ''} ${isTyping ? styles["typing"] : ''}`}>
      <div className={styles["ai-summary-header"]}>
        <div className={styles["ai-summary-content"]}>
          <div className={styles["ai-icon"]} />
          <span className={styles["ai-label"]}>AI总结: </span>
          {isLoading ? "正在加载中..." : (displayText || "暂无总结数据")}
        </div>
      </div>
    </div>
  );
};

export default AISummary; 